﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Network
{
    public class ClientManager
    {
        public string IP { get; set; }
        public int Port { get; set; }
        public bool Connected { get { return Client.Connected; } }
        public TcpClient Client;
        public NetworkStream NetworkStream;
        public delegate void ReceiveDataEventHandler(byte[] data);
        public event ReceiveDataEventHandler OnReceiveData;

        public ClientManager(string ip, int port)
        {
            IP = ip;
            Port = port;
            Client = new TcpClient();
        }

        public void Connect()
        {
            Client.Connect(new IPEndPoint(IPAddress.Parse(IP), Port));
            Console.WriteLine("CLIENT: Connected to port " + Port.ToString());
            NetworkStream = Client.GetStream();
            Thread thrdReceive = new Thread(new ThreadStart(ReceiveServerData));
            thrdReceive.Start();
        }

        public void Disconnect()
        {
            Console.WriteLine("CLIENT: Disconnected");
            Client.Close();
            NetworkStream.Close();
        }

        public void SendMessageToServer(string message)
        {
            PacketWriter packetwriter = new PacketWriter();
            packetwriter.Write((ushort)Headers.Text);
            packetwriter.Write(message);
            byte[] databuffer = packetwriter.GetBytes();
            NetworkStream.Write(databuffer, 0, databuffer.Length);
            NetworkStream.Flush();
        }

        public void SendDataToServer(byte[] data)
        {
            NetworkStream.Write(data, 0, data.Length);
            NetworkStream.Flush();
        }

        private void ReceiveServerData()
        {
            try
            {
                int buffersize;
                byte[] databuffer;

                while (true)
                {
                    databuffer = new byte[4086];
                    buffersize = NetworkStream.Read(databuffer, 0, databuffer.Length);
                    Array.Resize(ref databuffer, buffersize);

                    if (OnReceiveData != null) OnReceiveData(databuffer);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.ToString());
            }
        }
    }
}
